import React, { useState } from 'react';
import styled from 'styled-components';
import { userRegister, userLogin, userInfo } from '../utils/request';
import AlertModal from './AlertModal'; // 确保路径正确

const ModalWrapper = styled.div<{ visible: boolean }>`
    display: ${({ visible }) => (visible ? 'block' : 'none')};
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5); /* 半透明的黑色遮罩层 */
    z-index: 999; /* 确保遮罩层在最上层 */
`;

const Modal = styled.div<{ visible: boolean }>`
    display: ${({ visible }) => (visible ? 'flex' : 'none')};
    align-items: center;
    flex-direction: column;
    position: fixed;
    top: 50%;
    left: 50%;
    width: 420px;
    padding: 20px;
    box-sizing: border-box;
    transform: translate(-50%, -50%);
    border: 1px solid rgba(180, 173, 173, 0.114);
    border-radius: 20px;
    box-shadow: 0px 8px 8px -4px rgba(16, 24, 40, 0.02), 0px 10px 40px -4px rgba(16, 24, 40, 0.02);
    background: rgb(255, 255, 255);
    z-index: 1000; /* 确保 Modal 在遮罩层上面 */
    .close-icon {
        width: 34px;
        height: 34px;
        position: absolute;
        top: -44px;
        right: 0;
        border-radius: 5px;
        background: rgb(255, 255, 255);
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        img {
            width: 18px;
            height: 18px;
        }
    }
    h2 {
        width: 100%;
        color: rgb(22, 16, 16);
        font-family: Roboto;
        font-size: 30px;
        font-weight: 700;
        line-height: 35px;
        text-align: left;
    }
    h3 {
        margin-top: 5px;
        width: 100%;
        color: rgb(180, 173, 173);
        font-family: Roboto;
        font-size: 16px;
        font-weight: 400;
        line-height: 26px;
        text-align: left;
    }
    .form-group {
        margin-top: 20px;
        width: 100%;
    }
    label {
        display: block;
        margin-bottom: 2px;
        color: rgb(22, 16, 16);
        font-family: Roboto;
        font-size: 12px;
        font-weight: 400;
        line-height: 20px;
        text-align: left;
    }
    input[type='text'],
    input[type='password'] {
        width: 100%;
        height: 56px;
        border: 1px solid #0095dd;
        border-radius: 10px;
        padding: 8px;
        box-sizing: border-box;
    }
    .checkbox-group {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: flex-start;
        margin-top: 16px;
        color: rgb(22, 16, 16);
        font-family: Roboto;
        font-size: 16px;
        font-weight: 400;
        line-height: 26px;
        text-align: left;
        input[type='checkbox'] {
            margin-right: 12px;
        }
    }
    .top-button {
        margin-top: 20px;
        width: 100%;
        height: 56px;
        display: flex;
        flex-direction: row;
        justify-content: center;
        align-items: center;
        gap: 10px;
        padding: 20px;
        border: 0;
        border-radius: 10px;
        background: #0095dd;
        color: rgb(255, 255, 255);
        font-family: Roboto;
        font-size: 16px;
        font-weight: 400;
        line-height: 26px;
        text-align: center;
        cursor: pointer;
        transition: background-color 0.3s ease;

        &:hover {
            background-color: #0077b6;
        }
    }
    .bottom-button {
        margin-top: 10px;
        width: 100%;
        height: 56px;
        display: flex;
        flex-direction: row;
        justify-content: center;
        align-items: center;
        gap: 10px;
        padding: 20px;
        box-sizing: border-box;
        color: #0095dd;
        font-family: Roboto;
        font-size: 16px;
        font-weight: 400;
        line-height: 26px;
        text-align: center;
        border: 1px solid #0095dd;
        border-radius: 10px;
        cursor: pointer;
        transition: background-color 0.3s ease, color 0.3s ease;

        &:hover {
            background-color: #0095dd;
            color: #ffffff;
        }
    }
`;

interface AuthModalProps {
    visible: boolean;
    onClose: () => void;
    onSwitch: () => void;
    isLogin: boolean;
    setIsLogin: (isLogin: boolean) => void;
}

const AuthModal: React.FC<AuthModalProps> = ({ visible, onClose, onSwitch, isLogin, setIsLogin }) => {
    const [userId, setUserId] = useState('');
    const [password, setPassword] = useState('');
    const [confirmPassword, setConfirmPassword] = useState('');
    const [passwordError, setPasswordError] = useState('');
    const [rememberMe, setRememberMe] = useState(false);

    // 新增 AlertModal 的状态
    const [isAlertOpen, setIsAlertOpen] = useState<boolean>(false);
    const [alertTitle, setAlertTitle] = useState<string>('');
    const [alertMessage, setAlertMessage] = useState<string>('');

    const handleLogin = async () => {
        try {
            const loginResponse = await userLogin({ userId, password });
            const { token } = loginResponse.data;
            localStorage.setItem('token', token);
            if (rememberMe) {
                localStorage.setItem('userId', userId);
                localStorage.setItem('password', password);
            }

            // 获取用户信息并存入本地
            const userInfoResponse = await userInfo({ Authorization: `Bearer ${token}` });
            const userData = userInfoResponse.data;
            localStorage.setItem('userInfo', JSON.stringify(userData));

            // 替换 alert
            setAlertTitle('登录成功');
            setAlertMessage('您已成功登录。');
            setIsAlertOpen(true);

            onClose();
            setIsLogin(true);
        } catch (error: any) {
            // 替换 alert
            const errorMsg = error.response?.data?.message || error.message || '登录失败';
            setAlertTitle('登录失败');
            setAlertMessage(`登录失败: ${errorMsg}`);
            setIsAlertOpen(true);
            onClose();
        }
    };

    const handleRegister = async () => {
        if (password !== confirmPassword) {
            setPasswordError('密码不一致');
            return;
        }
        setPasswordError('');
        try {
            const registerResponse = await userRegister({ userId, password });
            if (registerResponse.data.registerStatus) {
                // 替换 alert
                setAlertTitle('注册成功');
                setAlertMessage('您已成功登录。');
                setIsAlertOpen(true);

                const loginResponse = await userLogin({ userId, password });
                const { token } = loginResponse.data;
                localStorage.setItem('token', token);

                // 获取用户信息并存入本地
                const userInfoResponse = await userInfo({ Authorization: `Bearer ${token}` });
                // console.log(userInfoResponse);
                const userData = userInfoResponse.data;
                localStorage.setItem('userInfo', JSON.stringify(userData));

                onClose();
                setIsLogin(true);
            } else {
                // 替换 alert
                setAlertTitle('注册失败');
                setAlertMessage('注册失败: 用户已存在');
                setIsAlertOpen(true);
            }
        } catch (error: any) {
            // 替换 alert
            const errorMsg = error.response?.data?.message || error.message || '注册失败';
            setAlertTitle('注册失败');
            setAlertMessage(`注册失败: ${errorMsg}`);
            setIsAlertOpen(true);
            onClose();
        }
    };

    const handleAlertClose = () => {
        setIsAlertOpen(false);
    };

    return (
        <>
            <ModalWrapper visible={visible} onClick={onClose} />
            <Modal visible={visible}>
                <div className="close-icon" onClick={onClose}>
                    X
                </div>
                {isLogin ? (
                    <>
                        <h2>欢迎</h2>
                        <h3>请登录</h3>
                        <div className="form-group">
                            <label>账号</label>
                            <input type="text" value={userId} onChange={(e) => setUserId(e.target.value)} />
                        </div>
                        <div className="form-group">
                            <label>密码</label>
                            <input type="password" value={password} onChange={(e) => setPassword(e.target.value)} />
                        </div>
                        <div className="checkbox-group">
                            <input
                                type="checkbox"
                                checked={rememberMe}
                                onChange={(e) => setRememberMe(e.target.checked)}
                            />
                            <label>记住密码</label>
                        </div>
                        <button className="top-button" onClick={handleLogin}>
                            登录
                        </button>
                        <button className="bottom-button" onClick={onSwitch}>
                            注册
                        </button>
                    </>
                ) : (
                    <>
                        <h2>创建账户</h2>
                        <h3>请输入详细信息</h3>
                        <div className="form-group">
                            <label>账号</label>
                            <input type="text" value={userId} onChange={(e) => setUserId(e.target.value)} />
                        </div>
                        <div className="form-group">
                            <label>密码</label>
                            <input type="password" value={password} onChange={(e) => setPassword(e.target.value)} />
                        </div>
                        <div className="form-group">
                            <label>请重复密码</label>
                            <input
                                type="password"
                                value={confirmPassword}
                                onChange={(e) => setConfirmPassword(e.target.value)}
                            />
                            {passwordError && <p style={{ color: 'red' }}>{passwordError}</p>}
                        </div>
                        <button className="top-button" onClick={handleRegister}>
                            注册
                        </button>
                        <button className="bottom-button" onClick={onSwitch}>
                            返回登录
                        </button>
                    </>
                )}
            </Modal>
            {/* 集成 AlertModal */}
            <AlertModal
                isOpen={isAlertOpen}
                title={alertTitle}
                message={alertMessage}
                onClose={handleAlertClose}
            />
        </>
    );
};

export default AuthModal;
